package com.jacen.fzxs.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.jacen.fzxs.entity.DictItemEntity;
import com.jacen.fzxs.entity.ImageEntity;
import com.jacen.fzxs.entity.WallCustomerEntity;
import com.jacen.fzxs.entity.WallEntity;
import com.jacen.fzxs.service.IDictItemService;
import com.jacen.fzxs.service.IImageService;
import com.jacen.fzxs.service.IWallCustomerService;
import com.jacen.fzxs.service.IWallService;
import com.jacen.fzxs.util.DateUtils;
import com.jacen.fzxs.util.EntityUtils;
import com.jacen.fzxs.util.ExcelUtils;
import com.jacen.fzxs.util.ServletUtils;
import com.jacen.fzxs.util.Utils;

/**
 * 墙体Controller
 * @author Jacen
 *
 */
@Controller
public class WallController extends BaseController {

	@Resource
	private IWallService wallService;
	@Resource
	private IWallCustomerService wcService;
	@Resource
	private IDictItemService itemService;
	@Resource
	private IImageService imageService;

	private static final Logger logger = LoggerFactory.getLogger(WallController.class);

	@RequestMapping("/wall/list.do")
	public String list(HttpServletRequest request,Integer curPage, ModelMap modelMap) throws Exception {
		Map<String, String> params = ServletUtils.getParameterMap(request);
		List<Map<String, Object>> list = wallService.getPage(getPager(curPage,request), params);
		List<DictItemEntity> tradeList = itemService.getList(DictItemController.trade);// 获取行业类型

		modelMap.addAttribute("list", list);
		modelMap.addAttribute("tradeList", tradeList);
		modelMap.addAttribute("province", params.get("province"));
		modelMap.addAttribute("city", params.get("city"));
		modelMap.addAttribute("county", params.get("county"));
		modelMap.addAttribute("cname", params.get("cname"));
		modelMap.addAttribute("area", params.get("area"));
		modelMap.addAttribute("lv", params.get("lv"));
		modelMap.addAttribute("tradeNum", params.get("trade"));
		modelMap.addAttribute("price", params.get("price"));
		modelMap.addAttribute("endTime", params.get("endTime"));
		modelMap.addAttribute("status", params.get("status"));
		modelMap.addAttribute("username", params.get("username"));
		modelMap.addAttribute("tel", params.get("tel"));

		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->查询墙体列表，" + "第"+(curPage==null?1:curPage.intValue()) +"页");
		return "wall/list";
	}

	@RequestMapping(value = "/wall/insert.do", method = RequestMethod.GET)
	public String enterInsert(HttpServletRequest request, String qs, ModelMap modelMap) {
		List<DictItemEntity> tradeList = itemService.getList(DictItemController.trade);// 获取行业类型
		modelMap.addAttribute("tradeList", tradeList);
		logger.info("用户：" + getLocalUser(request).getUserName() + "进入新增墙体页面");
		return "wall/insert";
	}

	@RequestMapping(value = "/wall/update.do", method = RequestMethod.GET)
	public String enterUpdate(HttpServletRequest request, String id, ModelMap modelMap) throws Exception {
		WallEntity entity = wallService.getById(id);
		WallCustomerEntity wcEntity = wcService.getByKey("wid", id);
		List<ImageEntity> images = imageService.getList(id);
		List<DictItemEntity> tradeList = itemService.getList(DictItemController.trade);// 获取行业类型
		modelMap.addAttribute("tradeList", tradeList);
		modelMap.addAttribute("wall", entity);
		modelMap.addAttribute("wcEntity", wcEntity);
		modelMap.addAttribute("images", images);
		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "进入修改墙体页面，id=" + id);
		return "wall/update";
	}

	@RequestMapping(value = "/wall/update.do", method = RequestMethod.POST)
	@ResponseBody
	public String postUpdate(HttpServletRequest request, WallEntity wallEntity, WallCustomerEntity wcEntity, String wcid) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			wallEntity.setCreateTime(DateUtils.getNowFormatTime(DateUtils.NORMAL_FORMAT));
			wallService.update(wallEntity);
			if (wcid == null || "".equals(wcid)) {
				if (!"".equals(wcEntity.getCname())) {
					wcEntity.setId(EntityUtils.createId32());
					wcService.insert(wcEntity);
				}
			} else {
				wcEntity.setId(wcid);
				wcService.update(wcEntity);
			}
			logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "修改墙体信息，id=" + wcid);

			resultMap.put("code", 1);
			return JSON.toJSONString(resultMap);
		} catch (Exception e) {
			resultMap.put("code", 0);
			return JSON.toJSONString(resultMap);
		}
	}

	@RequestMapping(value = "/wall/insert.do", method = RequestMethod.POST)
	@ResponseBody
	public String postInsert(WallEntity wallEntity, WallCustomerEntity wcEntity, HttpServletRequest request,
			HttpServletResponse response) {
		String wid = "";
		try {
			wid = EntityUtils.createId32();
			wallEntity.setId(wid);
			wallEntity.setCreateTime(DateUtils.getNowFormatTime("yyyy-MM-dd HH:mm:ss"));
			wallService.insert(wallEntity);
			if (!wcEntity.getCname().equals("")) {
				wcEntity.setId(EntityUtils.createId32());
				wcEntity.setWid(wid);
				wcService.insert(wcEntity);
			}
			logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "新增墙体信息：" + wid);
		} catch (Exception e) {
			logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "新增墙体信息，发生异常：" + e.getMessage());
			return Utils.errorJsonResp(e.getMessage());
		}
		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "新增墙体信息，id=" + wid);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 1);
		resultMap.put("wid", wid);
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(value = "/wall/delete.do", method = RequestMethod.GET)
	public String delete(HttpServletRequest request, String id) throws Exception {
		wallService.deleteAndRel(id);
		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "删除墙体,id" + id);
		return "redirect:/wall/list.do";
	}

	@RequestMapping("/wall/batchDelete.do")
	public String batchDelete(HttpServletRequest request, String[] ids) throws Exception {
		for (String id : ids) {
			wallService.deleteAndRel(id);
		}
		logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "批量删除墙体：" + ids.length + "条");
		return "redirect:/wall/list.do";
	}

	@RequestMapping(value = "/wall/view.do", method = RequestMethod.GET)
	public String view(HttpServletRequest request, String id, ModelMap modelMap, String qs) throws Exception {
		try{
			WallEntity wallEntity = wallService.getById(id);
			WallCustomerEntity wcEntity = wcService.getByKey("wid", wallEntity.getId());
			List<ImageEntity> images = imageService.getList(id);
			DictItemEntity item = new DictItemEntity();
			if (wcEntity != null){
				item = itemService.getItemByGroupAndName("trade", wcEntity.getTrade());
			}
			modelMap.addAttribute("tradeName", NullToStr(item.getItemValue()));
			modelMap.addAttribute("wall", wallEntity);
			modelMap.addAttribute("wc", wcEntity);
			modelMap.addAttribute("images", images);
			modelMap.addAttribute("qs", qs);
			logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->查看墙体信息：id" + id + "用户名：" + wallEntity.getUsername());
			return "wall/view";
		}catch(Exception e){
			e.printStackTrace();
			return "error";
		}
		
	}

	@RequestMapping("/wall/batchExport.do")
	public synchronized void export(HttpServletRequest request, HttpServletResponse response) {
		HSSFWorkbook wb = null;
		OutputStream os = null;
		try {
			Map<String, String> params = ServletUtils.getParameterMap(request);
			List<Map<String, Object>> wallList = wallService.getList(params);

			String fileName = DateUtils.getNowFormatTime("yyyyMMdd") + "墙体数据.xls";
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setContentType("application/x-msdownload");
			String dispposition = "=?UTF-8?Q?attachment;filename=" + fileName;
			response.setHeader("Content-Disposition", dispposition);

			// 创建Excel的工作书册 Workbook,对应到一个excel文档
			wb = new HSSFWorkbook();
			// 创建Excel的工作sheet,对应到一个excel文档的tab
			HSSFSheet sheet = wb.createSheet("墙体信息");

			HSSFPatriarch patriarch = sheet.createDrawingPatriarch();// 图片
			HSSFClientAnchor anchor = null;

			// 设置excel每列宽度
			sheet.setColumnWidth(0, 5000);
			sheet.setColumnWidth(1, 5000);
			sheet.setColumnWidth(2, 5000);
			sheet.setColumnWidth(3, 2000);
			sheet.setColumnWidth(4, 3500);
			sheet.setColumnWidth(5, 3000);
			sheet.setColumnWidth(6, 2000);
			sheet.setColumnWidth(7, 2000);
			sheet.setColumnWidth(8, 5000);
			sheet.setColumnWidth(9, 2000);
			sheet.setColumnWidth(10, 3000);
			sheet.setColumnWidth(11, 3000);
			sheet.setColumnWidth(12, 2000);
			sheet.setColumnWidth(13, 2000);
			sheet.setColumnWidth(14, 3000);
			sheet.setColumnWidth(15, 3000);
			sheet.setColumnWidth(16, 2000);
			sheet.setColumnWidth(17, 5000);

			// 创建字体样式
			HSSFFont font = wb.createFont();
			font.setFontName("Verdana");
			font.setColor(HSSFColor.BLUE.index);

			// 创建单元格样式
			HSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index2);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

			style.setFont(font);// 设置字体
			// 创建Excel的sheet的一行
			HSSFRow row = sheet.createRow(0);

			HSSFCell cell = row.createCell(0);
			cell.setCellStyle(style);
			cell.setCellValue("省");
			cell = row.createCell(1);
			cell.setCellStyle(style);
			cell.setCellValue("市");
			cell = row.createCell(2);
			cell.setCellStyle(style);
			cell.setCellValue("县");
			cell = row.createCell(3);
			cell.setCellStyle(style);
			cell.setCellValue("乡镇");
			cell = row.createCell(4);
			cell.setCellStyle(style);
			cell.setCellValue("地址");
			cell = row.createCell(5);
			cell.setCellStyle(style);
			cell.setCellValue("姓名");
			cell = row.createCell(6);
			cell.setCellStyle(style);
			cell.setCellValue("联系方式");
			cell = row.createCell(7);
			cell.setCellStyle(style);
			cell.setCellValue("宽");
			cell = row.createCell(8);
			cell.setCellStyle(style);
			cell.setCellValue("高");
			cell = row.createCell(9);
			cell.setCellStyle(style);
			cell.setCellValue("面积");
			cell = row.createCell(10);
			cell.setCellStyle(style);
			cell.setCellValue("级别");
			cell = row.createCell(11);
			cell.setCellStyle(style);
			cell.setCellValue("价格");
			cell = row.createCell(12);
			cell.setCellStyle(style);
			cell.setCellValue("客户名称");
			cell = row.createCell(13);
			cell.setCellStyle(style);
			cell.setCellValue("客户行业");
			cell = row.createCell(14);
			cell.setCellStyle(style);
			cell.setCellValue("租赁时间");
			cell = row.createCell(15);
			cell.setCellStyle(style);
			cell.setCellValue("到期时间");
			cell = row.createCell(16);
			cell.setCellStyle(style);
			cell.setCellValue("状态");

			cell = row.createCell(17);
			cell.setCellStyle(style);
			cell.setCellValue("备注");

			cell = row.createCell(18);
			cell.setCellStyle(style);
			cell.setCellValue("图片");

			// 设置单元格内容格式
			HSSFCellStyle style1 = wb.createCellStyle();
			style1.setDataFormat(HSSFDataFormat.getBuiltinFormat("yyyy-MM-dd"));

			for (int i = 0; i < wallList.size(); i++) {
				row = sheet.createRow(i + 1);
				row.setHeight((short) 500);
				Map<String, Object> entity = wallList.get(i);
				cell = row.createCell(0);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("province").toString());
				cell = row.createCell(1);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("city").toString());
				cell = row.createCell(2);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("county").toString());
				cell = row.createCell(3);
				cell.setCellStyle(style1);
				cell.setCellValue(NullToStr(entity.get("town")));
				cell = row.createCell(4);
				cell.setCellStyle(style1);
				cell.setCellValue(NullToStr(entity.get("address")));
				cell = row.createCell(5);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("username").toString());
				cell = row.createCell(6);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("tel").toString());
				cell = row.createCell(7);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("width").toString());
				cell = row.createCell(8);
				cell.setCellStyle(style1);
				cell.setCellValue(NullToStr(entity.get("high")));
				cell = row.createCell(9);
				cell.setCellStyle(style1);
				cell.setCellValue(NullToStr(entity.get("area")));
				cell = row.createCell(10);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("lvname").toString());
				cell = row.createCell(11);
				cell.setCellStyle(style1);
				cell.setCellValue(NullToStr(entity.get("price")));
				cell = row.createCell(12);
				cell.setCellStyle(style1);
				cell.setCellValue(NullToStr(entity.get("cname")));
				cell = row.createCell(13);
				cell.setCellStyle(style1);
				cell.setCellValue(NullToStr(entity.get("tradename")));
				cell = row.createCell(14);
				cell.setCellValue(NullToStr(entity.get("rentTime")));
				cell = row.createCell(15);
				cell.setCellValue(NullToStr(entity.get("endTime")));
				cell = row.createCell(16);
				cell.setCellStyle(style1);
				String status = NullToStr(entity.get("status"));
				if (status.equals("0"))
					status = "空白";
				if (status.equals("1"))
					status = "自租";
				if (status.equals("2"))
					status = "他租";
				cell.setCellValue(status);

				cell = row.createCell(17);
				cell.setCellStyle(style1);
				cell.setCellValue(entity.get("memo").toString());

				// 图片
				int j = 0;
				List<ImageEntity> images = imageService.getList(entity.get("id").toString());
				if (images == null || images.size() == 0)
					continue;
				String url = "";
				for (ImageEntity image : images) {
					url = image.getUrl();
					String path = UploadController.UPLOAD_PATH + "\\" + image.getWid() + "\\" + image.getUrl().substring(url.lastIndexOf("/") + 1);
					File jpgfile = new File(path);// barName 为统计图片在服务器上的路径
					ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();// 字节输出流，用来写二进制文件
					try {
						BufferedImage bufferImg = ImageIO.read(jpgfile);
						ImageIO.write(bufferImg, "jpg", byteArrayOut);
					} catch (IOException e) {
						continue;
					}
					anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) (18 + j), i + 1, (short) (18 + j), i + 1);
					patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));// 将统计图片添加到Excel文件中
					j++;
				}
			}
			os = response.getOutputStream();
			wb.write(os);
			os.close();
			logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "导出墙体列表excel,文件：" + fileName + ",共" + wallList.size()
					+ "条");
		} catch (Exception e) {
			logger.info(DateUtils.getNowFormatTime("yyyy-MM-dd hh:mm:ss")+"->用户：" + getLocalUser(request).getUserName() + "导出墙体列表excel异常：" + e.getMessage());
		}

	}

	@RequestMapping("/wall/import.do")
	@ResponseBody
	public String excelImport(MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response) {
		try {
			File temp = new File(UploadController.UPLOAD_PATH_TEMP+uploadFile.getName()+".xls");
			FileCopyUtils.copy(uploadFile.getBytes(), temp);
			DictItemEntity item = null;
			List<String[]> dataList = ExcelUtils.excelToData(temp, 0, 1);
			if (dataList.size() == 0)
				return Utils.errorJsonResp("excel文件中无数据");
			if (dataList.get(0).length != 18)
				Utils.errorJsonResp("excel数据模板不正确，重新下载模板");

			WallEntity wallEntity = null;
			WallCustomerEntity wcEntity = null;
			String wid = "";
			for (String[] data : dataList) {
				try {
					wid = EntityUtils.createId32();
					wallEntity = new WallEntity();
					wallEntity.setId(wid);
					if (!NullToStr(data[0]).endsWith("省"))
						data[0] = data[0] + "省";
					wallEntity.setProvince(NullToStr(data[0]));
					if (!NullToStr(data[1]).endsWith("市"))
						data[1] = data[1] + "市";
					wallEntity.setCity(NullToStr(data[1]));
					wallEntity.setCounty(data[2]);
					wallEntity.setTown(NullToStr(data[3]));
					wallEntity.setAddress(NullToStr(data[4]));
					wallEntity.setUsername(NullToStr(data[5]));
					wallEntity.setTel(NullToStr(data[6]));
					wallEntity.setWidth(NullToStr(data[7]));
					wallEntity.setHigh(NullToStr(data[8]));
					wallEntity.setArea(NullToStr(data[9]));
					int lv = 2;// 默认值：2-中
					if (NullToStr(data[10]).equals("优"))
						lv = 0;
					if (NullToStr(data[10]).equals("良"))
						lv = 1;
					wallEntity.setLv(lv);// 等级
					wallEntity.setPrice(NullToStr(data[11]));
					int status = 0;// 默认值：0-空白
					if (NullToStr(data[16]).equals("自租"))
						status = 1;
					if (NullToStr(data[16]).equals("他租"))
						status = 2;
					wallEntity.setStatus(status);
					wallEntity.setMemo(NullToStr(data[17]));// 备注

					if (!NullToStr(data[12]).equals("")) {
						wcEntity = new WallCustomerEntity();
						wcEntity.setId(EntityUtils.createId32());
						wcEntity.setWid(wid);
						wcEntity.setCname(data[12]);
						item = itemService.getByKey("itemValue", data[13]);
						int trade = item == null ? 4 : Integer.valueOf(item.getItemName());// 默认为：4-广告行业
						wcEntity.setTrade(trade);// 行业
						wcEntity.setRentTime(data[14]);
						wcEntity.setEndTime(data[15]);
						wcService.insert(wcEntity);
					}
				} catch (Exception e) {
					logger.error(e.getMessage());
					return Utils.errorJsonResp("excel导入发生异常，请检查是否按照要求填写");
				}
				wallEntity.setCreateTime(DateUtils.getNowFormatTime("yyyy-MM-dd HH:mm:ss"));
				wallService.insert(wallEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return Utils.errorJsonResp("excel导入发生异常，请检查excel模板或与管理员联系");
		}
		return Utils.normalJsonResp();
	}

	/**
	 * 空字符串处理
	 * @param obj
	 * @return
	 */
	private String NullToStr(Object obj) {
		return obj == null ? "" : obj.toString();
	}
	
	public static void main(String[] args) {
		long totalRecords = 11222;
		System.out.println(Long.valueOf(totalRecords).intValue());
	}

}
